layui.use(['jquery', 'febs', 'laydate', 'form', 'validate', 'treeSelect', 'eleTree'], function () {
    var $ = layui.$,
        febs = layui.febs,
        layer = layui.layer,
        eleTree = layui.eleTree,
        form = layui.form,
        laydate = layui.laydate,
        formSelects = layui.formSelects,
        $view = $('#tenant-edit'),
        $creatAppId = $view.find('#creatAppId'),
        $creatAppSecret = $view.find('#creatAppSecret'),
        $resetAppSecret = $view.find('#resetAppSecret'),
        $access = $view.find('#systemInterfacingFlg'),
        $statisticsFlag = $view.find('#statisticsFlag'),
        $attribute = $view.find('#attributeSelect'),
        $scale = $view.find('#scaleSelect'),
        $parent = $view.find('#parentSelect'),
        $economyType = $view.find('#economyTypeSelect'),
        $economyMajorType = $view.find('#economyMajorTypeSelect'),
        $economyMinorType = $view.find('#economyMinorTypeSelect'),
        $industryTradeType = $view.find('#industryTradeTypeSelect'),
        $inherentLevel = $view.find('#inherentLevelSelect'),
        $reachCondition = $view.find('#reachConditionSelect'),
        $trafficReachCondition = $view.find('#trafficReachConditionSelect'),
        validate = layui.validate;

    initDictItemSelect();

    form.verify(validate);
    form.render();

    function initDictItemSelect() {
        //单位属性
        febs.initDictItemSelect($attribute, 'SAFETY_COMPANY_ATTRIBUTE', tenant.attribute, null);
        //公司规模
        febs.initDictItemSelect($scale, 'SAFETY_COMPANY_SCALE', tenant.scale, null);
        //经济类型
        febs.initDictItemSelect($economyType, 'SAFETY_ECONOMY_TYPE', tenant.economyType, null);
        //经济行业大类
        febs.initDictItemSelect($economyMajorType, 'SAFETY_ECONOMY_MAJOR_TYPE', tenant.economyType, null);
        //经济行业小类
        febs.initDictItemSelect($economyMinorType, 'SAFETY_ECONOMY_MINOR_TYPE', tenant.economyType, null);
        // 工贸企业分类
        febs.initDictItemSelect($industryTradeType, 'SAFETY_INDUSTRY_TRADE_TYPE', tenant.industryTradeType, null);
        // 最高固有风险等级
        febs.initDictItemSelect($inherentLevel, 'SAFETY_INHERENT_LEVEL', tenant.inherentLevel, null);
        // 达标情况
        febs.initDictItemSelect($reachCondition, 'SAFETY_REACH_CONDITION', tenant.reachCondition, null);
        // 达标情况
        febs.initDictItemSelect($trafficReachCondition, 'SAFETY_REACH_CONDITION', tenant.trafficReachCondition, null);
        // 上级单位
        febs.initDictItemSelectSelf($parent, tenantSelect, tenant.parentId, null);

    }

    laydate.render({
        elem: "#reachDate", done: function (value, date) {
        },
    })

    laydate.render({
        elem: "#trafficReachDate", done: function (value, date) {
        },
    })

    form.verify({
        secondTabRequired: function (value, item) {
            if (null != value && value.trim().length === 0) {
                return "【" + $("#second-tab-li").text() + "】:" + (item.placeholder || item.getAttribute('placeholder'));
            }
        },
        thirdTabRequired: function (value, item) {
            if (null != value && value.trim().length === 0) {
                return "【" + $("#third-tab-li").text() + "】:" + (item.placeholder || item.getAttribute('placeholder'));
            }
        }
    });

    formSelects.render();

    formSelects.config('tenant-type-select', {
        searchUrl: ctx + 'tenant/getTenantTypeSelect',
        data: {
            // tenantId: currentTenantId
        },
        response: {
            statusCode: 200
        },
        beforeSuccess: function (id, url, searchVal, result) {
            var data = result.data;
            var tranData = [];
            for (var i = 0; i < data.length; i++) {
                tranData.push({
                    name: data[i].itemName,
                    value: data[i].itemCode
                })
            }
            result.data = tranData;
            return result;
        },
        success: function () {
            if (tenant && tenant.tenantType != null) {
                formSelects.value('tenant-type-select', tenant.tenantType.split(','));
            }
        },
        error: function (id, url, searchVal, err) {
            console.error(err);
            febs.alert.error('获取公司类型列表失败');
        }
    });


    initFormValue();

    function initFormValue() {
        if (tenant) {
            form.val("tenant-edit-form", {
                "tenantId": tenant.tenantId,
                "parentTenantId": tenant.parentTenantId,
                "tenantName": tenant.tenantName,
                "shortName": tenant.shortName,
                // "contact": tenant.contact,
                // "contactNumber": tenant.contactNumber,
                // "address": tenant.address,
                "appId": tenant.appId,
                "appSecret": tenant.appSecret,
                "utype": tenant.utype,
                "tenantType": tenant.tenantType,
                "tenantCode": tenant.tenantCode,
                "businessCode": tenant.businessCode,
                "legalCredentialType": tenant.legalCredentialType,
                "legalCredentialNo": tenant.legalCredentialNo,
                "legalName": tenant.legalName,
                "legalMobile": tenant.legalMobile,
                "tenantCreditCode": tenant.tenantCreditCode,
                "administrativeRegion": tenant.administrativeRegion,
                "country": tenant.country,
                "city": tenant.city,
                "street": tenant.street,
                "tenantBrief": tenant.tenantBrief,
                "businessAddress": tenant.businessAddress,
                "registeredAddress": tenant.registeredAddress,
                "scale": tenant.scale,
                "attribute": tenant.attribute,
                "affiliation": tenant.affiliation,
                "principal": tenant.principal,
                "principalTelephone": tenant.principalTelephone,
                "principalMobile": tenant.principalMobile,
                "principalEmail": tenant.principalEmail,
                "safetyUserName": tenant.safetyUserName,
                "safetyUserTelephone": tenant.safetyUserTelephone,
                "safetyUserMobile": tenant.safetyUserMobile,
                "safetyUserEmail": tenant.safetyUserEmail,
                "emergencyManageCount": tenant.emergencyManageCount,
                "certifiedSafetyCount": tenant.certifiedSafetyCount,
                "employeeSituation": tenant.employeeSituation,
                "manageCondition": tenant.manageCondition,
                "manageScope": tenant.manageScope,
                "holdingSituation": tenant.holdingSituation,
                "industryField": tenant.industryField,
                "economyType": tenant.economyType,
                "economyMajorType": tenant.economyMajorType,
                "economyMinorType": tenant.economyMinorType,
                "majorFlg": tenant.majorFlg,
                "industryTradeType": tenant.industryTradeType,
                "inherentLevel": tenant.inherentLevel,
                "majorRisk": tenant.majorRisk,
                "chemicalFlg": tenant.chemicalFlg,
                "majorHazard": tenant.majorHazard,
                "responsibilityFlg": tenant.responsibilityFlg,
                "riskControl": tenant.riskControl,
                "safetyGearFlag": tenant.safetyGearFlag,
                "safetyProduction": tenant.safetyProduction,
                "majorContent": tenant.majorContent,
                "reachCondition": tenant.reachCondition,
                "reachDate": tenant.reachDate,
                "trafficReachCondition": tenant.trafficReachCondition,
                "trafficReachDate": tenant.trafficReachDate,
                "systemInterfacingFlg": tenant.systemInterfacingFlg,
                "statisticsFlag": tenant.statisticsFlag,
            });
            if (tenant.systemInterfacingFlg === '1') {
                $("#systemInterfacingFlg").attr("checked", "true");
                $("#appInfoDiv").show();
            } else {
                $("#systemInterfacingFlg").removeAttr("checked");
            }
            if (tenant.statisticsFlag === '1') {
                $("#statisticsFlag").attr("checked", "true");
            } else {
                $("#statisticsFlag").removeAttr("checked");
            }
            form.render('checkbox');
        }
    }

    // 状态 - 开关操作
    form.on('switch(systemInterfacingFlg)', function (data) {
        var status = data.elem.checked;
        if (!status) {
            $("#appInfoDiv").hide();
            $('#appIdSpan').text();
            $('#appId').val('');
            $('#appSecretSpan').text();
            $('#appSecret').val('');
        } else {
            if (!tenant.appId) {
                creatAppId();
                creatAppSecret();
            }
            $("#appInfoDiv").show();
        }
    });

    form.on('submit(tenant-tab-edit-form-submit)', function (data) {
        addOrUpdateRole(data.field);
        return false;
    });

    function addOrUpdateRole(data) {
        data.systemInterfacingFlg = $access.is(':checked') ? '1' : '0';
        data.statisticsFlag = $statisticsFlag.is(':checked') ? '1' : '0';
        if (data.tenantId && data.tenantId.length > 0) {
            febs.modal.confirm('修改公司信息', '确定修改公司信息？', function (index) {
                febs.postArray(ctx + 'tenant/update', data, function () {
                    layer.closeAll();
                    febs.alert.success('修改公司成功');
                    $('#febs-tenant').find('#query').trigger('click');
                });
            });
        } else {
            febs.modal.confirm('保存公司信息', '确定保存公司信息？', function (index) {
                febs.postArray(ctx + 'tenant', data, function () {
                    layer.closeAll();
                    febs.alert.success('新增公司成功');
                    $('#febs-tenant').find('#query').trigger('click');
                });
            });
        }
    }

    $creatAppSecret.on('click', function () {
        febs.postArray(ctx + 'tenant/creatAppSecret', null, function (r) {
            if (r.code === 200) {
                form.val("tenant-edit-form", {
                    "appSecret": r.data
                });
                $('#appSecretSpan').text(r.data);
                $('#creatAppSecret').hide();
            } else {
                layer.msg(r.message);
            }
        });
    });

    $resetAppSecret.on('click', function () {
        creatAppSecret();
    });

    function creatAppSecret() {
        febs.postArray(ctx + 'tenant/creatAppSecret', null, function (r) {
            if (r.code === 200) {
                form.val("tenant-edit-form", {
                    "appSecret": r.data
                });
                $('#appSecretSpan').text(r.data);
                // $('#resetAppSecret').hide();
            } else {
                layer.msg(r.message);
            }
        });
    }

    $creatAppId.on('click', function () {
        creatAppId();
    });

    function creatAppId() {
        febs.postArray(ctx + 'tenant/creatAppId', null, function (r) {
            if (r.code === 200) {
                form.val("tenant-edit-form", {
                    "appId": r.data
                });
                $('#appIdSpan').text(r.data);
                $('#creatAppId').hide();
            } else {
                layer.msg(r.message);
            }

        });
    }

});
